package com.liduanwei.update.app;

import com.liduanwei.update.entity.AppInfo;
import com.liduanwei.update.entity.RemoteAppInfo;
import com.liduanwei.update.util.DownloadUtil;
import com.liduanwei.update.util.FileUtil;
import com.liduanwei.update.util.PrintUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Wei on 17/10/3.
 */
public abstract class AbstractChecker {
    protected Date lastCheckDate = readLastCheckDate();

    protected AppInfo currentAppInfo;
    protected RemoteAppInfo lastRemoteAppInfo;


    private boolean isDownloading = false;


    /**
     * 读取当前版本信息(如 从磁盘文件中读取)
     *
     * @return
     */
    abstract AppInfo loadCurrentAppInfo();

    abstract RemoteAppInfo loadRemoteAppInfo();

    protected boolean hasNewVersion(AppInfo currentAppInfo) {
        RemoteAppInfo remoteAppInfo = loadRemoteAppInfo();
//        return (remoteAppInfo != null && remoteAppInfo.getVersionCode() > currentAppInfo.getVersionCode());
        return (remoteAppInfo != null && remoteAppInfo.getVersionCode() != currentAppInfo.getVersionCode());
    }


    private DownloadUtil.DecompressCallback decompressCallback = new DownloadUtil.DecompressCallback() {
        @Override
        public void onComplete(boolean isSuccessfully) {
            isDownloading = false;

            /*更新内存中当前版本信息到最新版*/
            if (isSuccessfully) {
                AbstractChecker.this.currentAppInfo = new AppInfo(lastRemoteAppInfo.getVersionCode(), lastRemoteAppInfo.getVersionName());
            }

            onNewestVersionComplete(isSuccessfully);
        }
    };

    protected void downloadAndDecompress(boolean forceIgnoreExpire) throws IOException {

        if (isDownloading) {
            PrintUtil.Companion.print("### 已在下载中:" + this.getClass().getSimpleName());
            return;
        }

        if (!forceIgnoreExpire && !checkExpire()) {
            return;
        }
        boolean newVersion = hasNewVersion(currentAppInfo == null ? loadCurrentAppInfo() : currentAppInfo);
        lastCheckDate = new Date();
        saveLastCheckDate();
        if (!newVersion) {
            return;
        }
        isDownloading = true;
        DownloadUtil.downloadZipFileAndDecompress(loadRemoteAppInfo().getZipFileUrl(), getClass().getSimpleName(), decompressCallback);
    }

    protected Date readLastCheckDate() {
        String lastCheckDateFile = "./last_check_date_" + this.getClass().getSimpleName();
        try {
            byte[] data = FileUtil.readFile(lastCheckDateFile);
            return new Date(Long.parseLong(new String(data)));
        } catch (FileNotFoundException ex) {
            this.lastCheckDate = new Date(0);
            saveLastCheckDate();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    protected void saveLastCheckDate() {
        try {
            String lastCheckDateFile = "./last_check_date_" + this.getClass().getSimpleName();
            FileUtil.writeFile(lastCheckDateFile, String.valueOf(lastCheckDate.getTime()).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    abstract boolean checkExpire();


    /**
     * 新版下载和解压完成
     */
    protected void onNewestVersionComplete(boolean isSuccessfully) {
        PrintUtil.Companion.print("###新版下载&解压执行完成: [ " + this.getClass().getSimpleName() + " ], 结果:" + isSuccessfully);
    }

    public void start() {
        this.start(false);
    }

    /**
     * @param forceIgnoreExpire 忽略过期检查强制拉取新版本
     */
    public void start(boolean forceIgnoreExpire) {
        try {
            this.downloadAndDecompress(forceIgnoreExpire);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void setLastRemoteAppInfo(RemoteAppInfo remoteAppInfo) {
        this.lastRemoteAppInfo = remoteAppInfo;
    }

    public RemoteAppInfo getLastRemoteAppInfo() {
        return this.lastRemoteAppInfo;
    }


    public boolean isDownloading() {
        return isDownloading;
    }
}
